package cn.edu.abtu.utils;

import cn.edu.abtu.entity.SysPermission;
import cn.edu.abtu.vo.RouterVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/*
 * 生成菜单树
 * */
public class MenuTree {


    /**
     * 生成路由
     *
     * @param permissionList 菜单列表
     * @param parentId       父级菜单
     * @return
     */
    public static List<RouterVo> makeRouter(List<SysPermission> permissionList, Long parentId) {
        List<RouterVo> routerList = new ArrayList<RouterVo>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<SysPermission>())
                .stream().filter(item -> item != null && item.getParentId().equals(parentId))
                .forEach(item -> {
                    RouterVo router = new RouterVo();
                    router.setName(item.getName());
                    router.setPath(item.getPath());
                    if (item.getParentId() == 0L) {
                        router.setComponent("Layout");
                        router.setAlwaysShow(true);
                    } else {
                        router.setComponent(item.getUrl());
                        router.setAlwaysShow(false);
                    }
                    router.setMeta(router.new Meta(item.getLabel(), item.getIcon(), item.getCode().split(",")));
                    List<RouterVo> children = makeRouter(permissionList, item.getId());
                    router.setChildren(children);
                    routerList.add(router);
                });
        return routerList;
    }

    /**
     * 生成菜单树
     *
     * @param permissionList
     * @param parentId
     * @return
     */
    public static List<SysPermission> makeMenuTree(List<SysPermission> permissionList, Long parentId) {
        //创建集合保存菜单
        List<SysPermission> menuList = new ArrayList<SysPermission>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<SysPermission>())
                .stream().filter(item -> item != null && Objects.equals(item.getParentId(), parentId))
                .forEach(item -> {
                    SysPermission permission = new SysPermission();
                    BeanUtils.copyProperties(item, permission);
                    List<SysPermission> children = makeMenuTree(permissionList, item.getId());
                    permission.setChildren(children);
                    menuList.add(permission);
                });
        return menuList;
    }

}
